package snack;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 * 贪吃蛇客户端
 * @author lz
 *
 */
public class SnackClient extends JFrame{
	
	private Snack snack;
	private Piece piece;
	
	public SnackClient() {
		MyComponent mc = new MyComponent();
		mc.setBackground(Color.black);
		add(mc);
		setTitle("贪吃蛇"); //设置标题
		setSize(800, 600); //设置大小
		setLocationRelativeTo(null); // 位于屏幕中间
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭程序
		setVisible(true); //可见
		setResizable(false); //不可改变大小
		
		snack = new Snack();
		
		addKeyListener(new MyKeyListener());
		new PaintThread().start();
	}
	
	/**
	 * main 函数
	 * @param args
	 */
	public static void main(String[] args) {
		SnackClient sc = new SnackClient();
	}
	
	private class MyComponent extends JPanel {
		
		 protected void paintComponent(Graphics g) {
			 
		    super.paintComponent(g);   
		    
		   
		    snack.draw(g, true);
		    snack.draw(g, false);
		   
		 }
	}
	
	/**
	 * 刷新游戏界面线程
	 * @author lz
	 *
	 */
	private class PaintThread extends Thread {
		
		@Override
		public void run() {
			while(true) {
				repaint();
				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	/**
	 * 键盘监听器
	 * @author lz
	 *
	 */
	private class MyKeyListener extends KeyAdapter {
		@Override
		public void keyPressed(KeyEvent e) {
			snack.keyPress(e);
		}
		
		@Override
		public void keyReleased(KeyEvent e) {
			snack.keyRelease(e);
		}
	}
	
}
